package com.frxuexi.apps.viewmodel

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.frxuexi.apps.AppState
import com.frxuexi.apps.entity.Apps
import com.frxuexi.apps.intent.AppIntent
import com.frxuexi.apps.repository.NetRepository
import com.frxuexi.lib_http.download.DownloadState
import com.frxuexi.lib_http.download.DownloadUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import java.io.File

class NetViewModel : ViewModel() {

    val netRepository by lazy { NetRepository() }

    val netChannel = Channel<AppIntent>(Channel.UNLIMITED)

    private var _netSatte = MutableStateFlow<AppState>(AppState.onLoading)
    val netState: StateFlow<AppState>
        get() = _netSatte

    private var _downSatte = MutableStateFlow<DownloadState>(DownloadState.onLoading)
    val downState: StateFlow<DownloadState>
        get() = _downSatte

    init {
        viewModelScope.launch {
            netChannel.consumeAsFlow().collect {
                when (it) {
                    is AppIntent.selClientApp -> {
                        selClientApp()
                    }
                    is AppIntent.downloadApk->{
                        downloadApk(it.apps,it.path)
                    }
                    else -> {}
                }
            }
        }
    }

    fun selClientApp() {
        viewModelScope.launch {
            val map = mapOf(Pair("userId", 1), Pair("page", 1))
            netRepository.selClientApp(map).flowOn(Dispatchers.IO).catch {
                Log.i("===",it.message.toString())
            }
                .collect {
                    if(it.statusCode==200){
                        _netSatte.value=AppState.onSuccess(it.data!!)
                    }else{
                        _netSatte.value=AppState.onError(it.msg!!)
                    }
                }
        }
    }

    fun downloadApk(apk:Apps, path:String){
        viewModelScope.launch {
            DownloadUtil.download(apk.apkUrl,File(path))
                .flowOn(Dispatchers.IO)
                .catch {
                    it.printStackTrace()
                }.collect{
                    _downSatte.value=it
                }
        }
    }
}